package com.hong.atomic;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: Administrator
 * @Date: 2018/7/18 11:17
 * @Description:
 */
public class AtomicIntegerTest {
    /**
     * 1.可见性
     * 2.序列性
     * 3.不能保证原子性
     */
   /* private static volatile int value;*/
    private static Set<Integer> set = Collections.synchronizedSet(new HashSet<Integer>());

    public static void main(String[] args) throws InterruptedException {
        /*Thread t1 = new Thread() {
            @Override
            public void run() {
                int x = 0;
                while (x < 500) {
                    int temp = value;
                    System.out.println(Thread.currentThread().getName() + ":" + temp);
                    value += 1;
                    x++;
                }
            }
        };

        Thread t2 = new Thread() {
            @Override
            public void run() {
                int x = 0;
                while (x < 500) {
                    int temp = value;
                    System.out.println(Thread.currentThread().getName() + ":" + temp);
                    value += 1;
                    x++;
                    *//**
                     * value = value+1;
                     * (1)获取值来自内存
                     * （2）加1
                     * （3）赋值
                     * (4)刷新缓存
                     *//*
                }
            }
        };

        t1.start();
        t2.start();
        t1.join();
        t2.join();*/

       final AtomicInteger value = new AtomicInteger();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                int x = 0;
                while (x < 500) {
                    int v = value.get();
                    set.add(v);
                    System.out.println(Thread.currentThread().getName() + ":" + v);
                    x++;
                    value.getAndIncrement();
                }
            }
        };

        Thread t2 = new Thread() {
            @Override
            public void run() {
                int x = 0;
                while (x < 500) {
                    int v = value.get();
                    set.add(v);
                    System.out.println(Thread.currentThread().getName() + ":" + v);
                    x++;
                    value.getAndIncrement();
                }
            }
        };

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(set.size());

    }
}
